package com.example.xymarket.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;

import com.example.xymarket.common.Info;
import com.example.xymarket.myView.StatusBar;
import com.example.xymarket.R;
import com.example.xymarket.httpUtil.GoodsService;
import com.example.xymarket.httpUtil.ImageService;
import com.example.xymarket.common.MyFile;
import com.example.xymarket.common.MyHandler;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

public class InsertGoodsActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StatusBar.setStatusBarColor(this,StatusBar.yellow);
        setContentView(R.layout.activity_insert_goods);
        key_word_input=(EditText) findViewById(R.id.key_word_input);
        title_input=(EditText) findViewById(R.id.title_input);
        num_input=(EditText) findViewById(R.id.num_input);
        weight_input=(EditText) findViewById(R.id.weight_input);
        price_input=(EditText) findViewById(R.id.price_input);
        imageView=(ImageView) findViewById(R.id.chose_image);
    }

    private EditText key_word_input;
    private EditText title_input;
    private EditText num_input;
    private EditText weight_input;
    private EditText price_input;
    private ImageView imageView;
    private File file;

    @SuppressLint("HandlerLeak")
    public  final Handler handler = new Handler()
    {

        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what==2) {
                String uri=(String) msg.obj;
                InsertMyGoods(uri);
            }
            if(msg.what==-2) {
                Toast.makeText(getApplicationContext(),"图片上传失败",Toast.LENGTH_LONG).show();
            }
            if(msg.what==100) {
                Toast.makeText(getApplicationContext(),"商品上传成功",Toast.LENGTH_LONG).show();
            }
            if(msg.what==-100) {
                Toast.makeText(getApplicationContext(),"商品上传失败",Toast.LENGTH_LONG).show();
            }
        }
    };


    public void Insert(View view)
    {
        if(file==null)
        {
            Toast.makeText(this,"请选择图片",Toast.LENGTH_LONG).show();
            return;
        }
        MyHandler myHandler=new MyHandler(this,handler);
        ImageService imageService=new ImageService(myHandler);
        imageService.uploadImage(file);
    }

    public void InsertMyGoods(String imageUri)
    {
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("image", imageUri);
            map.put("title", "【" + key_word_input.getText().toString() + "】" + title_input.getText().toString() + " " +
                    weight_input.getText().toString() + "g");
            Spinner spinner = (Spinner) findViewById(R.id.spinner);
            int i = spinner.getSelectedItemPosition();
            map.put("categoryId", i + 1);
            map.put("soldQty", 0);
            map.put("merchantId", Info.getMyMerchant().getId());
            Double price = Double.parseDouble(price_input.getText().toString()) * 100;
            Integer p = price.intValue();
            map.put("price", p);
            map.put("stockQty", Integer.parseInt(num_input.getText().toString()));
            MyHandler myHandler = new MyHandler(this, handler);
            GoodsService goodsService = new GoodsService(myHandler);
            goodsService.InsertGoods(map);
        }
        catch (Exception e)
        {
            Toast.makeText(getApplicationContext(),"参数有误请检查参数！",Toast.LENGTH_LONG).show();
        }
    }


    public void ChoseImage(View view)
    {
        Intent intent = new Intent(Intent.ACTION_PICK, null);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(intent, 2);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 2) {
            // 从相册返回的数据
            Log.e(this.getClass().getName(), "Result:" + data.toString());
            if (data != null) {
                // 得到图片的全路径
                Uri uri = data.getData();
                imageView.setImageURI(uri);
                imageView.setDrawingCacheEnabled(true);
                Bitmap bitmap = Bitmap.createBitmap(imageView.getDrawingCache());
                imageView.setDrawingCacheEnabled(false);
                file= MyFile.getFile(bitmap);
            }
        }
    }

    public void clear(View view)
    {
        key_word_input.setText("");
        title_input.setText("");
        num_input.setText("");
        weight_input.setText("");
        price_input.setText("");
    }



    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN){
            Intent intent = new Intent(getApplicationContext(), MyShopActivity.class);
            startActivity(intent);overridePendingTransition(0, 0);
        }
        return super.onKeyDown(keyCode, event);
    }
}